import logging
import re
from app.models import db, User
import app.utils as utils

from flask import Blueprint, current_app, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity

privacy_controller = Blueprint('privacy_controller', __name__)

# 在请求到达前记录信息
@privacy_controller.before_request
def log_request_info():
    current_app.logger.info(f"收到请求: {request.method} {request.url}")
    if request.data:
        current_app.logger.debug(f"请求数据: {request.data.decode('utf-8')}")

# 在响应发送后记录信息
@privacy_controller.after_request
def log_response_info(response):
    current_app.logger.info(f"响应状态码: {response.status_code}")
    current_app.logger.debug(f"响应数据: {response.get_data(as_text=True)}")
    return response


# 下面开始是privacy_controller蓝图下的所有装饰器与配套函数 ————————————————————————

@privacy_controller.post('/risk-profile')
@jwt_required()
def submit_risk_profile():
    try:
        # 获取当前登录用户信息
        user_id = get_jwt_identity()
        db_user = db.session.query(User).filter_by(id=user_id).first()
        if not db_user:
            return jsonify({"error": "用户未找到"}), 404

        # 获取请求数据
        data = request.get_json()
        required_fields = [
            "age", "investmentGoal","expectedReturn","redemptionNeed","riskAcceptance",
            "incomeSource", "annualIncome","investableProportion","debtStatus",
            "investmentKnowledge", "investmentExperience","investmentDuration",
            "preferredProducts", "lossTolerance"
        ]

        # 验证必填字段
        for field in required_fields:
            if field not in data:
                return jsonify({"error": f"缺少字段 {field}"}), 400

        # 风险评分初始化 分越高 risk_level越高 越偏好风险 承担风险的能力越大
        risk_score = 0

        # 1. 根据年龄范围加分
        age_weights = {
            "under_18": 0,
            "18_30": 30,
            "31_40": 25,
            "41_50": 20,
            "51_64": 10,
            "65_above": 5
        }
        risk_score += age_weights.get(data["age"], 0)

        # 2. 根据投资目标加分
        goal_weights = {
            "education_retirement": 10,
            "personal_goals": 20,
            "wealth_growth": 30
        }
        risk_score += goal_weights.get(data["investmentGoal"], 0)

        # 3. 根据期望收益率加分
        return_weights = {
            "same_as_deposit": 5,
            "slightly_higher": 15,
            "much_higher": 30
        }
        risk_score += return_weights.get(data["expectedReturn"], 0)

        # 4. 根据是否有赎回需求加分
        redemption_weights = {
            "yes": 0,
            "not_sure": 10,
            "no": 20
        }
        risk_score += redemption_weights.get(data["redemptionNeed"], 0)

        # 5. 根据对不保本产品的风险接受程度加分
        risk_acceptance_weights = {
            "no": 0,
            "yes": 30
        }
        risk_score += risk_acceptance_weights.get(data["riskAcceptance"], 0)

        # 6. 根据主要收入来源加分
        income_source_weights = {
            "no_fixed_income": 0,
            "non_financial_income": 10,
            "salary": 15,
            "business_income": 20,
            "financial_income": 25
        }
        risk_score += income_source_weights.get(data["incomeSource"], 0)

        # 7. 根据年收入范围加分
        income_weights = {
            "under_50k": 5,
            "50k_200k": 15,
            "200k_above": 30
        }
        risk_score += income_weights.get(data["annualIncome"], 0)

        # 8. 根据投资资产占比加分
        proportion_weights = {
            "under_20%": 10,
            "20%-50%": 20,
            "above_50%": 30
        }
        risk_score += proportion_weights.get(data["investableProportion"], 0)

        # 9. 根据当前债务状况加分
        debt_weights = {
            "high": 0,
            "manageable": 10,
            "none": 20
        }
        risk_score += debt_weights.get(data["debtStatus"], 0)

        # 10. 根据投资知识水平加分
        knowledge_weights = {
            "none": 0,
            "basic": 15,
            "proficient": 30
        }
        risk_score += knowledge_weights.get(data["investmentKnowledge"], 0)

        # 11. 根据投资经验加分
        experience_weights = {
            "none": 0,
            "limited": 15,
            "rich": 30
        }
        risk_score += experience_weights.get(data["investmentExperience"], 0)

        # 12. 根据投资期限加分
        duration_weights = {
            "short_term": 10,
            "medium_term": 20,
            "long_term": 30
        }
        risk_score += duration_weights.get(data["investmentDuration"], 0)

        # 13. 根据偏好产品加分(可多选)
        product_weights = {
            "savings": 5,
            "fund": 15,
            "stocks": 20,
            "futures": 30,
            "others": 10
        }
        risk_score += sum(product_weights.get(p, 0) for p in data["preferredProducts"])

        # 14. 根据对亏损的容忍度加分
        loss_tolerance_weights = {
            "very_sensitive": 0,
            "neutral": 15,
            "risk_taker": 30
        }
        risk_score += loss_tolerance_weights.get(data["lossTolerance"], 0)

        current_app.logger.info(f"risk_score: {risk_score}")

        # 计算风险等级 (满分是395)
        if risk_score < 150:
            risk_level = "low"
        elif risk_score < 250:
            risk_level = "mid"
        else:
            risk_level = "high"

        current_app.logger.info(f"风险评分: {risk_score}，等级: {risk_level}")

        # 更新用户属性 - 修正拼写错误
        preferred_investment = data["preferredProducts"]
        preferred_horizen = data["investmentDuration"]  # 注意：这里是 "horizen" 不是 "borizon"

        # 赋值前打印调试信息
        current_app.logger.info(f"准备更新用户属性: "
                                f"risk_level={risk_level}, "
                                f"preferred_investment={preferred_investment}, "
                                f"preferred_horizen={preferred_horizen}")

        # 更新用户对象 - 确保使用正确的字段名
        db_user.risk_level = risk_level

        # 对于 JSON 字段，需要确保赋值正确的数据类型
        db_user.preferred_investment = preferred_investment  # 这应该是一个列表

        # 修正拼写错误：preferred_horizen 不是 preferred_borizon
        db_user.preferred_horizen = preferred_horizen

        # 提交事务
        db.session.commit()

        # 提交后立即查询数据库验证
        db.session.refresh(db_user)  # 刷新对象状态
        current_app.logger.info(f"更新后验证: "
                                f"risk_level={db_user.risk_level}, "
                                f"preferred_investment={db_user.preferred_investment}, "
                                f"preferred_horizen={db_user.preferred_horizen}")

        # 返回响应
        return jsonify({
            "message": "问卷提交成功",
        }), 200


    except Exception as e:
        return jsonify({"error": str(e)}), 500